"""
数据分析类
"""
import re
import xlrd
import numpy as np
import pandas as pd
from .UserException import NotNumError


class DataAnalyse:

    def __init__(self):
        self.data = dict()

    def load_data(self, year, path):
        """
        加载一年的数据
        """
        dy = xlrd.open_workbook(path)  # 年度数据
        sheets_list = dy.sheet_names()

        # 数据结构思路：利用字典，从年、省份、分类、行业逐层嵌套存储键值对
        dy_dict = dict()
        # 各表
        for sheet_name in sheets_list:
            table = dy.sheet_by_name(sheet_name)
            nrows, ncols = table.nrows, table.ncols
            dbc = [table.col_values(colx) for colx in range(ncols)]  # 各列数据组成的列表
            table_dict = {}  # 表字典

            # 针对不同表修改导入行数
            if sheet_name == 'Sum':
                row_range = list(range(1, nrows - 2)) + [nrows - 1]
            else:
                row_range = range(3, nrows)

            # 建立字典
            for i in range(1, ncols):
                col_dict = dict()  # 列字典
                for j in row_range:
                    try:
                        if type(dbc[i][j]) != float:
                            col_dict[dbc[0][j]] = 0
                            raise NotNumError(year, sheet_name, dbc[0][j], dbc[i][0])
                        else:
                            col_dict[dbc[0][j]] = float(dbc[i][j])
                    except NotNumError as n:
                        pass
                        # print(f"NotNumError!\nYear: {n.year}\nProvince: {n.province}\nIndustry: {n.industry}\n"
                        #      f"Source: {n.source}\n")
                table_dict[dbc[i][0]] = col_dict
            dy_dict[sheet_name] = table_dict
        self.data[year] = dy_dict

    def time_analyse(self, sheet, row, col, start, end):
        """
        时间分析
        """
        x = range(start, end + 1)
        y = []
        for i in x:
            y.append(self.data[i][sheet][col][row])
        return x, y

    def space_analyse(self, year, _type, industry='Sum', province=[]):
        """
        空间分析
        """
        data = self.data[year]
        c_list = province if province else list(data.keys())[1:]
        if industry == 'Sum':
            y = [data['Sum'][_type][c] for c in c_list]
        else:
            y = [data[c][_type][industry] for c in c_list]
        return c_list, y
